package middlewares

import (
	"net/http"

	"gitee.com/LangHuaHuachihua/blog-go/apps/user"
	"gitee.com/LangHuaHuachihua/blog-go/common"
	"gitee.com/LangHuaHuachihua/blog-go/ioc"
	"gitee.com/LangHuaHuachihua/blog-go/logger"
	"github.com/gin-gonic/gin"
)

func Auth(c *gin.Context) {

	logger.L().Debug().Msg("中间件")
	//cookie信息获取
	tk, err := c.Cookie(user.AUTH_COOKIE_NAME)
	if err != nil {
		common.NewResponse(c, 400, http.StatusUnauthorized, err.Error())
		c.Abort()
		return
	}

	if tk == "" {
		common.NewResponse(c, 400, http.StatusUnauthorized, "请登录")
		c.Abort()
		return
	}

	//检查token
	usvc := ioc.GetController(user.AppName).(user.Service)
	u, err := usvc.ValidateToken(c.Request.Context(), user.NewValidateTokenRequest(tk))
	if err != nil {
		common.NewResponse(c, 0, http.StatusUnauthorized, err.Error())
		return
	}
	//把user对象放到ctx中
	c.Set(user.REQUEST_CTX_KEY, u)
}
